import React from "react";
import { useAuth } from "context/auth-context";
import { Form, Input } from "antd";
import { LongBotton } from "unauthenticated-app";
import { useAsync } from "utils/use-async";
export const LoginScreen = ({
  onError,
}: {
  onError: (error: Error) => void;
}) => {
  /**
   * 调用接口
   */
  const { login, user } = useAuth();
  const { run, isLoading } = useAsync(undefined, { throwOnError: true });
  // values可以通过form.item的name属性值来推断
  const handleSubmit = async (values: {
    username: string;
    password: string;
  }) => {
    try {
      // FIXME 注意这里是异步的 trycatch不能直接捕获 一定要加上async和await
      await run(login(values));
    } catch (err) {
      // 这里需要用trycatch捕获不能用useAsync里返回的error 会造成同步和异步的混用
      onError(err);
    }
  };
  return (
    <Form onFinish={handleSubmit}>
      {user ? <div>登录成功，用户名{user?.name}</div> : null}
      <Form.Item
        name="username"
        rules={[{ required: true, message: "请输入用户名" }]}
      >
        <Input placeholder="用户名" type="text" id={"username"} />
      </Form.Item>
      <Form.Item
        name="password"
        rules={[{ required: true, message: "请输入密码" }]}
      >
        <Input placeholder="密码" type="password" id={"password"} />
      </Form.Item>
      <Form.Item>
        {/* antd Button自带loading属性 */}
        <LongBotton loading={isLoading} htmlType="submit" type="primary">
          登录
        </LongBotton>
      </Form.Item>
    </Form>
  );
};
